var util = require('../../utils/util.js')
var app = getApp();

// pages/main/main.js
Page({
  data: {
    hasAgent:true,
    imgUrls: [
      {
        // link: '/pages/map/map',
        url: 'https://www.ymg3.com/ymgImage/Page/p_xianhua.png'
      }, {
        // link: '/pages/logs/logs',
        url: 'https://www.ymg3.com/ymgImage/Page/chongcao.jpg'
      }, {
        // link: '/pages/mine/mine',
        url: 'https://www.ymg3.com/ymgImage/Page/zhujiang.jpg'
      }, {
        // link: '/pages/mine/mine',
        url: 'https://www.ymg3.com/ymgImage/Page/huawei.jpg'
      }
    ],
    hiddens: true,
    // indicatorDots: true,
    // autoplay: true,
    // interval2: 5000,
    // duration: 1000,
    userInfo: {},
    text: '',
    size: 24,
    interval: 20,// 时间间
    hasRoot: false,
    noRoot: true,
    isTime:true
  },
  alertTip: function () {//点击超市专区触发事件
    jumpsuper(this)
  },
  toSpike: function () {//进入秒团专区
    wx.navigateTo({ url: '../spike/spike?id=0' })
  }
  ,
  toDirect: function () {//点击跳转到直营专区
    wx.navigateTo({
      url: '../homepage/homepage',
    })
  },
  onLoad: function () {
   
    // app.getUserInfo(function (userInfo) {//调用app.js里面的获取用户唯一id以及用户姓名，头像的方法
    //   //更新数据
    //   that.setData({
    //     code: app.globalData.code,
    //     username: userInfo.nickName
    //   });
    //   that.update();
    //   // console.log(app.globalData.code)
    // });
  },
  onReady: function () {
    
    // 页面渲染完成
  },
  onShow: function () {
    getPersonLocation(this);//获取当前区域
   // getUserInfoss(this);
    // 页面显示
    var that = this;
    wx.getSystemInfo({//获取滑块的高宽
      success: function (res) {
        that.setData({
          winWidth: res.windowWidth,
          winHeight: res.windowHeight
        });
      }
    });
    // console.log(wx.getStorageSync('userid'))
    var that = this;
    getPersonSuperInfo(this)  //获取当前用户的超市id
    // console.log(app.globalData.hasRoot)

   
  },
  toSpikeDetail: function () {//点击今日秒杀跳转到详情页面
    // console.log(this.data.spikeid)
    if (this.data.spikeid) {
      wx.navigateTo({
        url: '../spikeDetaile/spikeDetaile?id=' + this.data.spikeid + "&agentId=" + this.data.agentId,
      })
    }
  },
  onHide: function () {
    // 页面隐藏

  },

  onUnload: function () {
    // 页面关闭
  },
  restartGet: function () {//根据不同的情况来重新获取用户的权限
    var that = this;
    wx.openSetting({
      success: function (res) {
        if (res.authSetting["scope.userInfo"] && res.authSetting["scope.userLocation"]) {
          that.setData({
            hasRoot: false,
            noRoot: true
          })
          getPersonLocation(that)
          getUserInfoss(that)
        }
      }
    })
    // if (wx.getStorageSync('checekgetUserInfo') != 1)conso {
    //   console.log(222)
    //   getUserInfoss(that)
    // }
    // if (wx.getStorageSync('checekgetPersonLocation') != 1) {
    //   console.log(333)
    //   getPersonLocation(that)
    // }
  }

})
/** 
 * 需要一个目标日期，初始化时，先得出到当前时间还有剩余多少秒
 * 1.将秒数换成格式化输出为XX天XX小时XX分钟XX秒 XX
 * 2.提供一个时钟，每10ms运行一次，渲染时钟，再总ms数自减10
 * 3.剩余的秒次为零时，return，给出tips提示说，已经截止
 */

// 定义一个总毫秒数，以一分钟为例。TODO，传入一个时间点，转换成总毫秒数

// var d1 = Date.now()//现在的好秒数
// var d2 = new Date(this.data.startDate, this.data.spikeTime)
// // var d2 = new Date(util.formatTime(new Date)[0], parseInt(util.formatTime(new Date)[1]), util.formatTime(new Date)[2], 19, 0, 0);//当天晚上七点的标准时间
// // console.log(d2)
// var d3 = d2.getTime();//当晚七点的毫秒数
// var total_micro_second = parseInt(d3 - d1);//剩余到晚上七点的毫秒数

/* 毫秒级倒计时 */
function count_down(that) {
   // 渲染倒计时时钟
   that.setData({
     clock1: date_format(that.data.total_micro_seconds).split(":")[0],
     clock2: ":" + date_format(that.data.total_micro_seconds).split(":")[1],
     clock3: ":" + date_format(that.data.total_micro_seconds).split(":")[2],
   });
   if (that.data.total_micro_seconds <= 0) {
     that.setData({
       clock1: "正在开抢",
       clock2: "",
       clock3: "",
     });
     // timeout则跳出递归
     return;
   }
   setTimeout(function () {
     // 放在最后--
     that.data.total_micro_seconds -= 1000;
     that.setData({
       total_micro_seconds: that.data.total_micro_seconds
     })
     count_down(that);
   }, 1000)
 
  
}
// 时间格式化输出，如03:25:19 86。每10ms都会调用一次
function date_format(micro_second) {
  // 秒数
  var second = Math.floor(micro_second / 1000);
  // 小时位
  var hr = Math.floor(second / 3600);
  // 分钟位
  var min = fill_zero_prefix(Math.floor((second - hr * 3600) / 60));
  // 秒位
  var sec = fill_zero_prefix((second - hr * 3600 - min * 60));// equal to => var sec = second % 60;
  // 毫秒位，保留2位
  var micro_sec = fill_zero_prefix(Math.floor((micro_second % 1000) / 10));
  return hr + " : " + min + " : " + sec;
}
// 位数不足补零
function fill_zero_prefix(num) {
  return num < 10 ? "0" + num : num
}

/**
 * 得到用户当前所在区域，列如四川省成都市成华区
 * @thisid 页面对象
 */

/**
 * 获取用户储存在本地的详细信息
 * @
 */
function getPersonSuperInfo(that) {
  wx.getStorage({
    key: 'superID',
    success: function (res) {
      that.setData({
        superID: res.data
      })
      app.superID = res.data
    }
  })
  wx.getStorage({
    key: 'superName',
    success: function (res) {
      that.setData({
        superName: res.data
      })
      app.superName = res.data
    }
  })

}

/**
 * 获取地址，如果没有就跳转到选地址的界面，如果有就直接跳转到超市
 */
function jumpsuper(that) {
  if (wx.getStorageSync('superID') != "") {
    wx.navigateTo({
      url: '/pages/shop/shop',
      success: function (res) { }
    })
  } else {
    wx.request({
      url: app.globalData.allUrl + "/addressAction/getAddress",
      data: {
        userID: wx.getStorageSync('userid')
      },
      method: 'GET', // OPTIONS, GET, HEAD, POST, PUT, DELETE, TRACE, CONNECT
      // header: {}, // 设置请求的 header
      success: function (res) {
        // success
        if (res.data) {//如果服务器有地址则跳转到超市页面
          //console.log(res.data)
          wx.setStorageSync('superID', res.data[res.data.length - 1].superId)
          wx.setStorageSync('superName', res.data[res.data.length - 1].superName)
          wx.navigateTo({
            url: '/pages/shop/shop',
            success: function (res) { }
          })
        } else {//
          moveToMap(that)
        }
      }
    })
  }
}

function moveToMap(that) {
  wx.chooseLocation({//调用地图，并将得到的地址发送至后台返回超市对象
    success: function (res) {

      that.setData({
        address: res.address,
        OL: res.longitude + ":" + res.latitude,
        lon: res.longitude,
        lat: res.latitude
        // lon: 104.104561,
        // lat: 30.714233
      });
      var addresses = res.address;
      app.longitude = res.longitude;
      app.latitude = res.latitude;
      wx.setStorageSync('longitude', res.longitude)
      wx.setStorageSync('latitude', res.latitude)
      wx.request({//将经纬度发送到后台并且从后台获取到对应的超市id以及超市名称
        url: app.globalData.allUrl + "/superMarketAction/skipPrefecture",
        data:
        {
          lon: that.data.lon,
          lat: that.data.lat
        },
        method: 'GET', // OPTIONS, GET, HEAD, POST, PUT, DELETE, TRACE, CONNECT
        // header: {}, // 设置请求的 header
        success: function (res) {
          //console.log(res.data)
          if (res.data != null) {
            wx.setStorageSync('superID', res.data.id);
            wx.setStorageSync('superName', res.data.name);
            getPersonSuperInfo(that);
            wx.navigateTo({ url: '/pages/shop/shop' })
            getStreet(that)//获取街道名称
            app.addressDetailes = addresses
          } else {
            wx.showToast({
              title: "附近暂无超市！",
              icon: "loading"
            })
            // console.log("设置超市信息失败")
          }
        }
      })
    }
  })
}
// that.setData({
//   "superName": res.data.name,
//   "superID": res.data.id
// })
// console.log(that.data.superName);


function requestSpikr(that, adcode) {//请求最近五天的秒杀信息
  wx.request({//请求最近五天的秒杀详情
    url: app.globalData.allUrl + "/seckillAction/getSeckillListByPostalcode",
    data: {
      postId: adcode
    },
    method: 'GET', // OPTIONS, GET, HEAD, POST, PUT, DELETE, TRACE, CONNECT
    // header: {}, // 设置请求的 header
    success: function (res) {
      // success
      //console.log(res.data)
      if (res.data) {
        that.setData({
          text: res.data[0].productName.substring(0, 8),
          spikeid: res.data[0].id,
          agentId: res.data[0].agentId,
          spikeTime: res.data[0].startTime,
          startDate: res.data[0].startDate,
          noseckills: false,
          hasseckills: true
        })
        // var d2 = new Date(that.data.startDate + " " + that.data.spikeTime)
        // console.log(d2)
        var d1 = Date.now();
        // var d2 = new Date(util.formatTime(new Date)[0], parseInt(util.formatTime(new Date)[1]), util.formatTime(new Date)[2], 19, 0, 0);
        var d2 = new Date(that.data.startDate + " " + that.data.spikeTime)
        var d3 = d2.getTime();
        var total_micro_second = parseInt(d3 - d1);
        that.setData({
          total_micro_seconds: total_micro_second
        })
        if (d3 - d1 > (60 * 60 * 24 * 1000)) {
          that.setData({
            clock1: "今日暂无秒杀",
            clock2: "",
            clock3: "",
          })
        } else {
          if (that.data.isTime){
            count_down(that);//倒计时
          }
          that.data.isTime=false;
        }
      } else {
        that.setData({
          noseckills: true,
          hasseckills: false
        })
      }
    }
  })
}

function getStreet(that) {
  wx.request({
    url: app.globalData.allUrl + "/utilAction/getmapinfo",
    data: {
      latitude: that.data.lat,
      longitude: that.data.lon
    },
    success: function (ops) {
      //console.log(ops.data)
      var newJson = ops.data.indexOf("{")
      var nextJson = ops.data.lastIndexOf(")")
      var userJson = ops.data.substring(newJson, nextJson)
      var res = JSON.parse(userJson)
      var addressDetaile = res.result.addressComponent.province + res.result.addressComponent.city + res.result.addressComponent.district + res.result.addressComponent.street
      // app.addressDetailes = addressDetaile;
      app.district = res.result.addressComponent.district
      // console.log( app.addressDetailes)
      //  wx.setStorageSync('adcode', res.result.addressComponent.adcode)
    }
  })
}


function getUserInfoss(that) { //调用登录接口
  wx.login({
    success: function (rese) {
      // console.log(rese.code)//用户为的唯一动态code
      // console.log(rese)
      wx.getUserInfo({
        success: function (res) {

          wx.setStorageSync('checekgetUserInfo', 1)
          if (that.data.noRoot) {
            that.setData({
              hasRoot: false,
              noRoot: true
            })
          }
          wx.setStorageSync('userInfo', res.userInfo)//将用户信息储存在本地
          // that.globalData.code=rese.code code每次登陆都会变化，所以传到后台让后台生成一个固定的userid，保存在本地，七天有效，用户打开商城时自动验证并登陆。
          // that.globalData.userInfo = res.userInfo
          // typeof cb == "function" && cb(that.globalData.userInfo)
          wx.request({
            url: app.globalData.allUrl + "/utilAction/wxLogin",
            data: {
              code: rese.code,
              username: res.userInfo.nickName
            },
            method: 'GET', // OPTIONS, GET, HEAD, POST, PUT, DELETE, TRACE, CONNECT
            // header: {}, // 设置请求的 header
            success: function (res) {
              // success
              // console.log(res.data)
              wx.setStorageSync('userid', res.data)
            }
          })
        }, fail: function () {
          wx.setStorageSync('checekgetUserInfo', 0)
          that.setData({
            hasRoot: true,
            noRoot: false
          })
        }
      })
    }
  })
}


function isAgent(that){//判断该区域有无代理商
   wx.request({
     url: app.globalData.allUrl + '/agentAction/getAgentInfoByagentRegionAndStatus',
     data:{
       agentRegion: app.adcode,
     },
     method:'GET',
     success:function(res){
       if(res.data){
         that.setData({
           hasAgent: true,
           noAgent: false
         })
       }else{
         that.setData({
           hasAgent: false,
           noAgent: true
         })
       }
     }

   })
}